import { defineStore } from "pinia";

const level = [0, 100, 150, 200, 255];
const maxLen = level.length - 1;
let index = 0;

export default defineStore("light", {
  state() {
    return {
      brightness: 0, // 0~255
      mode: 1, // 1(自动开关) 2(定时开关) 3(手动开关)
      timeRange: {
        start: new Date(1970, 0, 1, 18, 0, 0),
        end: new Date(1970, 0, 2, 6, 0, 0)
      }
    };
  },
  getters: {
    getBrightnessPercentage() {
      let per = (this.brightness / 255) * 100; // 获取百分比
      per = Math.round(per * 100) / 100; // 四舍五入，保留两位小数
      return per;
    }
  },
  actions: {
    setBrightness(value) {
      index = level.findIndex((v) => v == value);
      if (index === -1) {
        index = 0;
        return;
      }
      this.brightness = value;
    },
    setMode(value) {
      this.mode = value;
    },
    setTimeRange(start, end) {
      this.timeRange.start = start;
      this.timeRange.end = end;
    },
    increaseBrightness() {
      index++;
      if (index > maxLen) {
        index = maxLen;
        return false;
      }

      this.brightness = level[index];
      return true;
    },
    reduceBrightness() {
      index--;
      if (index < 0) {
        index = 0;
        return false;
      }

      this.brightness = level[index];
      return true;
    }
  }
});
